import time
from utils.file_handler import FileHandler

class Student:
    def __init__(self, name):
        self.name = name
        self.file_handler = FileHandler()
    
    def list_available_exams(self):
        """列出所有可用的试卷"""
        return self.file_handler.list_exams()
    
    def take_exam(self, exam_id):
        """答题"""
        # 加载试卷
        exam = self.file_handler.load_exam(exam_id)
        if not exam:
            raise Exception("试卷不存在")
        
        answers = []
        print("\n" + "="*20 + " 开始答题 " + "="*20)
        
        for i, q in enumerate(exam['questions'], 1):
            print(f"\n第{i}题：{q['question']}")
            answer = input("你的答案：")
            answers.append(answer)
        
        # 生成提交ID并保存答案
        submission_id = f"{self.name}_{exam_id}"
        submission = {
            'exam_id': exam_id,
            'student_name': self.name,
            'answers': answers,
            'timestamp': time.strftime("%Y-%m-%d %H:%M:%S")
        }
        
        self.file_handler.save_submission(submission_id, submission)
        return submission_id
    
    def view_results(self):
        """查看成绩"""
        results = []
        # 遍历所有结果文件
        for result_id in self.file_handler.list_results():
            if result_id.startswith(self.name + "_"):
                result = self.file_handler.load_results(result_id)
                if result:
                    results.append(result)
        return results
    
    def view_wrong_questions(self, exam_id):
        """查看指定试卷的错题"""
        submission_id = f"{self.name}_{exam_id}"
        
        # 加载答卷
        submission = self.file_handler.load_submission(submission_id)
        if not submission:
            raise Exception("未找到该试卷的答题记录")
        
        # 加载成绩和原试卷
        results = self.file_handler.load_results(submission_id)
        if not results:
            raise Exception("该试卷尚未批改")
            
        exam = self.file_handler.load_exam(exam_id)
        if not exam:
            raise Exception("原试卷不存在")
        
        # 整理错题信息
        wrong_questions = []
        for i, (question, student_answer, is_correct) in enumerate(
            zip(exam['questions'], submission['answers'], results['results']), 1):
            if not is_correct:
                wrong_questions.append({
                    'number': i,
                    'question': question['question'],
                    'your_answer': student_answer,
                    'correct_answer': question['answer']
                })
        
        return {
            'exam_id': exam_id,
            'score': results['score'],
            'total_questions': len(exam['questions']),
            'wrong_count': len(wrong_questions),
            'wrong_questions': wrong_questions,
            'submission_time': submission['timestamp']
        }